﻿using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using TicketMLib;

namespace TicketMProductsManipulators
{
    public class ProductsMan
    {
        #region Product Manipulation
        /// <summary>
        /// This method reads the existing products from ticket work item type for a given project.
        /// The arraylist that is returened is bound to a datagrid on Products.aspx page
        /// </summary>
        /// <param name="sProject">Represents the session variable that contains selected project</param>
        /// <returns></returns>
        public ArrayList GetProductsList(string sProject)
        {
            ArrayList Products = new ArrayList();
            try
            {
                #region Get Variable Values from existing config file
                string uName;
                string passwd;
                string domain;
                string tfs;
                string collection;
                string _project;
                Utils.SetGenVarValues(sProject, out uName, out passwd, out domain, out tfs, out collection, out _project);
                #endregion

                TfsTeamProjectCollection tpc = Utils.Connect2Tfs(uName, passwd, domain, tfs, collection);
                var wiStore = tpc.GetService<WorkItemStore>();
                var project = wiStore.Projects[_project];
                WorkItemType wiType = project.WorkItemTypes["Ticket"];
                XmlDocument doc1 = wiType.Export(true);
                XmlNode root1 = doc1.DocumentElement;
                XmlNodeList nodes = root1.SelectNodes("//FIELDS/FIELD[@name='Product']/ALLOWEDVALUES/LISTITEM");
                foreach (XmlNode product in nodes)
                {
                    Products.Add(product.Attributes["value"].Value);
                }
            }
            catch
            {

                throw;
            }
            return Products;
        }
        /// <summary>
        /// This method updates the Ticket work item type for the selected project by adding the new product in the products list
        /// </summary>
        /// <param name="newProduct">Name of the new product to add</param>
        /// <param name="sProject">Session variable that represents the selected project</param>
        /// <returns></returns>
        public string SetProductsList(string newProduct, string sProject)
        {
            string returnMsg;
            try
            {
                #region Get Variable Values from existing config file
                string uName;
                string passwd;
                string domain;
                string tfs;
                string collection;
                string _project;
                Utils.SetGenVarValues(sProject, out uName, out passwd, out domain, out tfs, out collection, out _project);
                #endregion

                //Connect to TFS and from the selected project get the XML of Ticket work item type definition
                TfsTeamProjectCollection tpc = Utils.Connect2Tfs(uName, passwd, domain, tfs, collection);
                var wiStore = tpc.GetService<WorkItemStore>();
                var project = wiStore.Projects[_project];
                WorkItemType wiType = project.WorkItemTypes["Ticket"];
                XmlDocument doc1 = wiType.Export(true);
                XmlNode root1 = doc1.DocumentElement;


                //Check if the product already exists
                XmlNode item = root1.SelectSingleNode("//FIELDS/FIELD[@name='Product']/ALLOWEDVALUES/LISTITEM[@value=\"" + newProduct + "\"]");
                if (item == null) //if the product does not exists in the Ticket work item of that project create a node for that product
                {
                    XmlNode node = root1.SelectSingleNode("//FIELDS/FIELD[@name='Product']/ALLOWEDVALUES");
                    if (node == null)
                    {
                        XmlNode productNode = root1.SelectSingleNode("//FIELDS/FIELD[@name='Product']");
                        XmlNode NewAllowedValuesNode = doc1.CreateNode(XmlNodeType.Element, "ALLOWEDVALUES", null);
                        productNode.AppendChild(NewAllowedValuesNode);
                        node = NewAllowedValuesNode;
                    }
                    XmlNode NewProductNode = doc1.CreateNode(XmlNodeType.Element, "LISTITEM", null);
                    XmlAttribute valueAttrib = doc1.CreateAttribute("value");
                    valueAttrib.Value = newProduct;
                    NewProductNode.Attributes.Append(valueAttrib);

                    //append it at appropriate place
                    node.AppendChild(NewProductNode);
                    //import the work item type back in the same project
                    project.WorkItemTypes.Import(doc1.DocumentElement);
                    returnMsg = "Product Added";
                }
                else
                {
                    returnMsg = "Same named product found";
                }
            }
            catch
            {

                throw;
            }
            return returnMsg;
        }
        #endregion
    }
}
